window.addEventListener('load', function () {
    var prev = document.querySelector('.prev')
    var next = document.querySelector('.next')
    var focus = document.querySelector('.focus')


    var num = 0;
    var index = null;
    // 点击小圆圈移动图片
    var focusWidth = focus.offsetWidth;
    // 控制小圆点切换
    var circle = 0;

    var flag = true;

    // 鼠标经过显示隐藏左右按钮
    focus.addEventListener('mouseenter', function () {
        prev.style.display = 'block';
        next.style.display = 'block';
        clearInterval(timer);
        timer = null;
    })

    focus.addEventListener('mouseleave', function () {
        prev.style.display = 'none';
        next.style.display = 'none';
        timer = setInterval(function () {
            next.click();
        }, 3000)
    })

    // 动态生成小圆点
    var ul = focus.querySelector('ul');
    var ol = focus.querySelector('.promo-nav');

    console.log(ul.children.length)
    for (var i = 0; i < ul.children.length; i++) {
        var li = document.createElement('li')
        // 自定义设置小圆点索引号
        li.setAttribute('index', i)
        // li插入ol
        ol.appendChild(li);
        // 绑定点击事件~排他思想
        li.addEventListener('click', function () {
            for (let i = 0; i < ol.children.length; i++) {
                ol.children[i].className = '';
            }
            this.className = 'selected'

            // 获取索引号
            index = this.getAttribute('index')
            console.log(index)
            num = index;

            // 点击小圆圈移动图片
            // focusWidth = focus.offsetWidth;

            // 索引乘图片宽度
            animate(ul, -index * focusWidth)
        })
    }
    ol.children[0].className = 'selected';

    ol.children[0].className = 'selected';
    var first = ul.children[0].cloneNode(true);
    ul.appendChild(first)

    // 点击右侧按钮图片切换
    next.addEventListener('click', function () {
        if (num == ul.children.length - 1) {
            ul.style.left = 0;
            num = 0;
        }
        num++;
        animate(ul, -num * focusWidth)
        circle++;
        // 判断
        if (num == ol.children.length) {
            num = 0;
        }
        circleChange()
    })
    // 点击左侧按钮图片切换
    prev.addEventListener('click', function () {
        if (num == 0) {
            num = ul.children.length - 1;
            ul.style.left = -num * focusWidth + 'px';
        }
        num--;
        animate(ul, -num * focusWidth)
        circle++;
        // 判断
        if (num == ol.children.length) {
            num = 0;
        }
        circleChange()
    })

    function circleChange() {
        for (var i = 0; i < ol.children.length; i++) {
            ol.children[i].className = '';
        }
        ol.children[num].className = 'selected';
    }

    // 自动播放
    var timer = setInterval(function () {
        next.click();
    }, 3000)

})